/*------------------------------------------------------------------------------
 * PROJ : PrototypeWithSpring
 * NAME : sculove.spring.framework.support.MultiCommonsMultipartResolver.java
 *        
 * Copyright 2009 sculove All rights reserved
 *------------------------------------------------------------------------------
*/
package sculove.spring.framework.support;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.fileupload.FileItem;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

/**
 * <pre>
 * sculove.spring.framework.support.MultiCommonsMultipartResolver.java
 * 
 * 요청시 multipart-form data 처리를 위한 Resolver 
 * 
 * </pre>
 * @date : 2009. 10. 9. 오후 4:13:06
 * @version :
 * @author : sculove
 */
public class MultiCommonsMultipartResolver extends CommonsMultipartResolver {

	/* Multi filename 적용을 위한 모듈 변경
	 * @see org.springframework.web.multipart.commons.CommonsFileUploadSupport#parseFileItems(java.util.List, java.lang.String)
	 */
	@Override
	protected MultipartParsingResult parseFileItems(List fileItems,
			String encoding) {
		Map multipartFiles = new HashMap();
		Map multipartParameters = new HashMap();

		// Extract multipart files and multipart parameters.
		for (Iterator it = fileItems.iterator(); it.hasNext();) {
			FileItem fileItem = (FileItem) it.next();
			if (fileItem.isFormField()) {
				String value = null;
				if (encoding != null) {
					try {
						value = fileItem.getString(encoding);
					}
					catch (UnsupportedEncodingException ex) {
						if (logger.isWarnEnabled()) {
							logger.warn("Could not decode multipart item '" + fileItem.getFieldName() +
									"' with encoding '" + encoding + "': using platform default");
						}
						value = fileItem.getString();
					}
				}
				else {
					value = fileItem.getString();
				}
				String[] curParam = (String[]) multipartParameters.get(fileItem.getFieldName());
				if (curParam == null) {
					// simple form field
					multipartParameters.put(fileItem.getFieldName(), new String[] { value });
				}
				else {
					// array of simple form fields
					String[] newParam = StringUtils.addStringToArray(curParam, value);
					multipartParameters.put(fileItem.getFieldName(), newParam);
				}
			}
			else {
				// multipart file field
				CommonsMultipartFile file = new CommonsMultipartFile(fileItem);

				/*
				 * 전자정부 표준 프레임웍 예
				 * (http://www.egovframe.go.kr/wiki/doku.php?id=egovframework:rte:sample:cvpl:file_upload_download)
				 * 
				 * 참조하여, 동일한 form name으로 map key를 구성하는 것이 아닌,
				 * 첨부하는 파일명으로 key를 구성함.
				 * 
				 * (단, 디렉토리가 다른 동일한 파일일 경우는 에러가 날수 있음
				 *  화면단에서 동일한 파일명 추출하여, 동일한 파일명을 올릴수 없다고 메시지 처리)
				 */
				//if (multipartFiles.put(file.getName(), file) != null) {
				if (multipartFiles.put(fileItem.getName(), file) != null) {
					throw new MultipartException(
							"Multiple files for field name [" + file.getName() + "] found - not supported by MultipartResolver");
				}
				if (logger.isDebugEnabled()) {
					logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize() +
							" bytes with original filename [" + file.getOriginalFilename() + "], stored " +
							file.getStorageDescription());
				}
			}
		}
		return new MultipartParsingResult(multipartFiles, multipartParameters);
	}
}
